package Servlet;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.ObjectMetadata;
import commons.BaseServlet;
import model.JsonModel;


import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.io.InputStream;

import java.util.UUID;

@WebServlet("/fileinput.do")
@MultipartConfig
public class FileInputServlet extends BaseServlet {
    // OSS 配置信息
    private static final String endpoint = "https://oss-cn-beijing.aliyuncs.com"; // OSS 外网节点或自定义域名
    private static final String accessKeyId = "LTAI5t8Fk6FBNzvE6vRm4YS3";
    private static final String accessKeySecret = "zipLN8pVnyv22hGDaAXoedTVPUUgIw";
    private static final String bucketName = "jxqandchx";

    public void addFiles(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        Part filePart = req.getPart("files"); // 获取上传的文件部分
        JsonModel jm = new JsonModel();

        try {
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        if (filePart != null && filePart.getSize() > 0) {
            String fileName = filePart.getSubmittedFileName();
            InputStream fileContent = filePart.getInputStream(); // 获取文件内容
            String uuid = UUID.randomUUID().toString().replaceAll("-", ""); // 生成唯一的文件名
            String objectName = uuid + "_" + fileName;

            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret); // 初始化OSS客户端
            try {
                ObjectMetadata metadata = new ObjectMetadata();
                metadata.setContentLength(filePart.getSize());
                ossClient.putObject(bucketName, objectName, fileContent, metadata); // 上传文件到OSS
                String url = endpoint.split("//")[0] + "//" + bucketName + "." + endpoint.split("//")[1] + "/" + objectName;
                System.out.println(url); // 打印文件URL

                jm.setCode(1);
                jm.setObj(url);
                writeJson(jm, resp);
            } finally {
                ossClient.shutdown(); // 关闭OSS客户端
            }
        }

    }
}
